import React, { useEffect, useMemo } from 'react';

import ConnectedCornerstoneViewport from './ConnectedCornerstoneViewport';
import OHIF from '@ohif/core';
import PropTypes from 'prop-types';

const { StackManager, getCornerstoneStack } = OHIF.utils;

const OHIFCornerstoneViewport = props => {
  const { viewportIndex, viewportData: { studies, displaySet }, children, customProps = {} } = props;

  useEffect(() => {
    return () => StackManager.clearStacks();
  }, []);

  /**
   * Obtain the CornerstoneTools Stack for the specified display set.
   *
   * @param {Object[]} studies
   * @param {String} StudyInstanceUID
   * @param {String} displaySetInstanceUID
   * @param {String} [SOPInstanceUID]
   * @param {Number} [frameIndex=1]
   * @return {Object} CornerstoneTools Stack
   */
  const stack = useMemo(() => getCornerstoneStack(studies, displaySet), [studies, displaySet]);

  let childrenWithProps = null;
  const {
    imageIds,
    currentImageIdIndex,
    // If this comes from the instance, would be a better default
    // `FrameTime` in the instance
    // frameRate = 0,
  } = stack;

  // TODO: Does it make more sense to use Context?
  if (children && children.length) {
    childrenWithProps = children.map((child, index) => {
      return (
        child &&
        React.cloneElement(child, {
          viewportIndex: this.props.viewportIndex,
          key: index,
        })
      );
    });
  }

  const newImageHandler = ({ currentImageIdIndex, sopInstanceUid }) => {
    const { StudyInstanceUID } = displaySet;

    if (currentImageIdIndex > 0) {
      onNewImage({
        StudyInstanceUID,
        SOPInstanceUID: sopInstanceUid,
        frameIndex: currentImageIdIndex,
        activeViewportIndex: viewportIndex,
      });
    }
  };

  return (
    <>
      <ConnectedCornerstoneViewport
        viewportIndex={viewportIndex}
        imageIds={imageIds}
        imageIdIndex={currentImageIdIndex}
        onNewImage={newImageHandler}
        onNewImageDebounceTime={700}
        {...customProps}
      />
      {childrenWithProps}
    </>
  );
}

OHIFCornerstoneViewport.propTypes = {
  viewportData: PropTypes.object,
  viewportIndex: PropTypes.number,
  children: PropTypes.node,
  customProps: PropTypes.object,
};

export default OHIFCornerstoneViewport;
